﻿using Managix.Infrastructure.Configuration;
using Managix.Repository.Entities.Base;
using Microsoft.EntityFrameworkCore;
using System;
using System.Reflection;
using System.Linq;

namespace Managix.Repository
{
    public partial class SqliteContext : DbContext
    {
        /// <summary>
        /// 自动生成DbSet
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var assembly = Assembly.GetExecutingAssembly();
            foreach (Type type in assembly.ExportedTypes)
            {
                if (type.IsClass && type != typeof(Root) && typeof(Root).IsAssignableFrom(type))
                {
                    var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault();

                    if (method != null)
                    {
                        method = method.MakeGenericMethod(new Type[] { type });
                        method.Invoke(modelBuilder, null);
                    }
                }
            }

            base.OnModelCreating(modelBuilder);
            // 指定程序集加载所有配置
            //this.GetType().Assembly 当前程序集
            //modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
            //modelBuilder.ApplyConfiguration(new BookEntityConfig());
            //demo Jinher.AMPX.PGS.EntityFramework.EntityConfigurations
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLazyLoadingProxies().UseSqlite(Configs.DbConfig.ConnectionString);
        }
    }
// Entity创建配置
//class BookEntityConfig : IEntityTypeConfiguration<Book>
//    {
//        public void Configure(EntityTypeBuilder<Book> builder)
//        {
//            builder.ToTable("T_Books");
//            builder.Property(e => e.Title).HasMaxLength(50).IsRequired();
//            builder.Property(e => e.AuthorName).HasMaxLength(20).IsRequired();
//        }
//    }
}



